class PhotosController < ApplicationController

	before_action :authenticate_user!

  def index
    @photos = current_user.photos
  end

	def new 
		@photo = Photo.new
	end
		
	def create
    if params[:file]
        pic = send_picture(params[:file], current_user)
        if pic.present?
          photo = Photo.create(:user_id => current_user.id, :src => pic)
          render :json => {:status => :success, :id=>photo.id, :src => "/assets/"+ pic , :title => pic ,:date => photo.created_at.strftime("%Y-%m-%d %H:%M")}.to_json
        end              
    else
       render :json => {:status => 'fail'}.to_json
    end
  end

 def destroy
    p = Photo.find(params[:id])
    if p.destroy
      render :json => {:status => :success}.to_json
    end  
  end  

  protected
    def send_picture(img, user)
      ext  = File.extname(img.original_filename)
      time = Time.now.to_i
      filename = "#{user.nickname}_#{time}#{ext}"  
      if File.open('app/assets/images/'+filename, 'wb') {|f| f.write img.tempfile.read } 
        return filename
      end 
    end

end 
